<?php

namespace App\Http\Admin\Services;

use App\Exceptions\InvalidRequestException;
use App\Http\Admin\Models\Admin;
use App\Http\Admin\Models\Permission;
use App\Http\Admin\Models\Role;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class AuthService extends BaseService
{

    public function token($attributes = [])
    {
        $attributes = array_only($attributes, ['username', 'password']);

        $user_id = $this->getUserId($attributes);

        //token保持时间
        $expire = !empty($attributes['expire']) ? $attributes['expire'] : 10;

        $str = $this->generateToken($user_id, $expire);

        return [
            'token' => $str
        ];

    }

    /*
     * 生成token  模仿jwt
     * @user_id 用户id
     * @expire 登录时长  默认10小时
     * */
    public function generateToken($user_id, $expire)
    {
        $expire_at = time() + $expire * 3600;
        return base64_encode($user_id . '_' . $expire_at);
    }


    public function getUserId($attributes = [])
    {
        //校验
        if (!paramExists($attributes, 'username') || !paramExists($attributes, 'password')) {
            throw new InvalidRequestException('请输入账号密码');
        }

        $user = Admin::where('username', $attributes['username'])->first();
        if (!$user) {
            throw new InvalidRequestException('无当前用户');
        }
        $salt = $user->salt;
        $password = $this->generatePassword($attributes['password'], $salt);

        $user = Admin::where('username', $attributes['username'])
            ->where('password', $password)->first();
        if (!$user) {
            throw new InvalidRequestException('账号或者密码错误');
        }

        $user_id = $user->id;

        return $user_id;

    }

    public function initUser($token = '')
    {
        //token解密过程
        try{
            $str = base64_decode($token);
            $arr = explode('_',$str);
            $user_id = $arr[0];
            $expire_at = $arr[1];
        }catch (\Exception $e){
            throw new InvalidRequestException('认证失效');
        }
        if($expire_at < time()){
            throw new InvalidRequestException('认证过期');
        }
        $user_info = $this->userInfo($user_id);
        return $user_info;
    }

    public function userInfo($user_id)
    {
        //查出admin
        $user = Admin::where('id',$user_id)->with('roles.permissions')->first();
        if(!$user){
            throw new InvalidRequestException('暂无该用户');
        }
        $roles_names = [];
        $permission_paths = [];
        $tmp_permissions = [];
        //归纳所有的权限路径
        if(!empty($user->roles)){
            $roles = $user->roles;
            foreach ($roles as $role){
                if(!empty($role->name)){
                    $roles_names[] = $role->name;
                }
                if(!empty($role->permissions)){
                    $permissions = $role->permissions;
                    foreach ($permissions as $permission){
                        $tmp_permissions[] = $permission;
                        if($permission->http_path){
                            $permission_paths[] = $permission->http_path;
                        }
                    }
                }
            }
        }
        $user->permissions = $tmp_permissions;
        $user->permission_paths = $permission_paths;
        $user->roles_names = $roles_names;
        return $user;
    }


}
